<script setup>
import ClaEdit from '@/views/liteflow/cla/ClaEdit.vue';
import ClaExec from '@/views/liteflow/cla/ClaExec.vue';
import { reactive, ref, watch } from 'vue';
import { VDataTableServer } from 'vuetify/labs/VDataTable';


//查询条件
const classId = ref()
const packagePath = ref()
const className = ref()
const classLoaderType = ref()
const classType = ref()

// 类型-下拉选择框
const classLoadList = reactive([
  { label: "应用程序类加载器", value: 0 },
  { label: "自定义类加载器", value: 1 },
])

// 表头
const headers = [
  {
    title: '类ID',
    key: 'classId',
  },
  {
    title: '类名称',
    key: 'className',
  },
  {
    title: '加载器类型',
    key: 'classLoaderType',
  },
  {
    title: 'class类型',
    key: 'classType',
  },
  {
    title: '是否为降级组件',
    key: 'isFallback',
  },
  {
    title: '版本号',
    key: 'version',
  },
  {
    title: '操作',
    key: 'actions',
    sortable: false,
  },
]

// 分页参数
const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

// 分页查询
const totalPage = ref(1) //总页数
const totalRows = ref(0) //总记录数
const list = ref([]) // 当前分页数据
const loadings = ref(false)

const fetchList = async (msg) => {
  loadings.value = true
  const res = await $ivyApi.post(API_URLS.lfDynamicClassPage,{
    classId: classId.value,
    packagePath: packagePath.value,
    className: className.value,
    classLoaderType: classLoaderType.value,
    classType: classType.value,
    options: options.value,
  })
  
  const data = res.data
  list.value = data.list
  totalPage.value = data.totalPage
  totalRows.value = data.totalRow
  options.value.page = data.page
  loadings.value = false

  if(typeof msg === 'string'){
    res.message = msg
    showMsg(res)
  }
}

watchEffect(fetchList)

// 监听 options 对象的变化，并在变化时调用 fetchList 方法
watch(options, async () => { await fetchList() }, { deep: true })

// 删除操作
const deleteId = ref('')
const deleteName = ref('')
const deleteVisible = ref(false)

const deleteOper = row => {
  deleteVisible.value = true
  deleteId.value = row.id
  deleteName.value = row.classId
}

const deleteAgreeOper = async (id) => {
  const res = await $ivyApi.post(API_URLS.lfDynamicClassDelete,{
    id: deleteId.value,
  })

  showMsg(res)
  fetchList()
  deleteVisible.value = false
  deleteId.value = ''
}

// 新增操作&编辑操作
const editKey = ref(1)
const operType = ref(0) // 操作类型：0新增，1更新
const currRow = ref({})
const addVisible = ref(false)

const addOper = () => {
  editKey.value++
  operType.value = 0
  currRow.value = {}
  addVisible.value = true
}

const addData = async (data) => {
  const res = await $ivyApi.post(API_URLS.lfDynamicClassAdd,data)
  showMsg(res)
  fetchList()
}

const updateOper = row => {
  editKey.value++
  operType.value = 1
  currRow.value = row
  addVisible.value = true
}

const updateData = async (data) => {
  const res = await $ivyApi.post(API_URLS.lfDynamicClassUpdate,data)
  showMsg(res)
  fetchList()
}

// 执行EL表达式
const execVisible = ref(false)

const execCmp = row => {
  currRow.value = row
  execVisible.value = true
}

// 回调信息
const snackbar = reactive(API_URLS.resultMsg)

const showMsg = res => {
  $resultMsg.show(res,snackbar)
}

const option = reactive({
  classLoaderType: {
    label: '',
    list: [],
  },
  classType: {
    label: '',
    list: [],
  },
  isFallback: {
    label: '',
    list: [],
  },
})

const classLoaderTypeOptions = reactive([])
const classTypeOptions = reactive([])
const isFallbackOptions = reactive([])

const optionSelect = async () => {
  const res = await $ivyApi.post(API_URLS.lfDynamicClassOption,{ fieldNames: 'classLoaderType,classType,isFallback' })
  Object.assign(option, res.data)
}

const getClassType = val => {
  const arr = option.classType ? option.classType.list : []
  var returnVal = val
  arr.forEach(element => {
    if(element.value == val){
      returnVal = element.title
    }
  })
  
  return returnVal
}

const getIsFallback = val => {
  const arr = option.isFallback ? option.isFallback.list : []
  var returnVal = val
  arr.forEach(element => {
    if(element.value == val){
      returnVal = element.title
    }
  })
  
  return returnVal
}

// 初始化
onMounted(() => {
  optionSelect()
})
</script>

<template>
  <section>
    <VSnackbar
      v-model="snackbar.msgVisible"
      location="top"
      :color="snackbar.msgColor"
    >
      {{ snackbar.msgContent }}
    </VSnackbar>
    <VRow>
      <VCol cols="12">
        <VCard>
          <!-- 👉 Filters -->
          <VCardText>
            <VRow>
              <VCol
                v-if="false"
                cols="12"
                sm="12"
              >
                <VAlert
                  border="start"
                  border-color="error"
                >
                  加载器类型推荐使用应用程序类加载器AppClassLoader。如果使用自定义类加载器，定义组件时会找不到类。
                </VAlert>
              </VCol>
              <VCol
                cols="12"
                sm="3"
              >
                <VTextField
                  v-model="classId"
                  label="类ID"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="3"
              >
                <VTextField
                  v-model="className"
                  label="类名称"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="3"
              >
                <VSelect
                  v-model="classLoaderType"
                  label="加载器类型"
                  :items="option.classLoaderType.list"
                  clearable
                  clear-icon="tabler-x"
                  item-title="title"
                  item-value="value"
                />
              </VCol>
              <VCol
                cols="12"
                sm="3"
              >
                <VSelect
                  v-model="classType"
                  label="class类型"
                  :items="option.classType.list"
                  clearable
                  clear-icon="tabler-x"
                  item-title="title"
                  item-value="value"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <AppSelect
                :model-value="options.itemsPerPage"
                :items="[
                  { value: 10, title: '10' },
                  { value: 20, title: '20' },
                  { value: 50, title: '50' },
                  { value: 100, title: '100' },
                ]"
                style="inline-size: 6.25rem;"
                @update:model-value="options.itemsPerPage = parseInt($event, 10)"
              />
            </div>
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VBtn
                :loading="loadings"
                :disabled="loadings"
                size="38"
                @click="fetchList('刷新成功')"
              >
                <VIcon
                  icon="tabler-refresh"
                  size="22"
                />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  刷新
                </VTooltip>
              </VBtn>
              <VBtn
                prepend-icon="tabler-plus"
                @click="addOper"
              >
                新增动态类
              </VBtn>
            </div>
          </VCardText>

          <VDivider />

          <!-- SECTION datatable -->
          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="list"
            :items-length="totalRows"
            :headers="headers"
            class="text-no-wrap"
            @update:options="options = $event"
          >
            <!-- Plan -->
            <template #item.classId="{ item }">
              <span class="font-weight-medium">{{ item.classId }}</span>
            </template>

            <template #item.className="{ item }">
              <span class="font-weight-medium">{{ item.className }}</span>
            </template>

            <template #item.classLoaderType="{ item }">
              <span class="font-weight-medium">
                <VChip
                  color="success"
                  size="small"
                  label
                  class="text-capitalize"
                >
                  {{ item.classLoaderType == 0 ? '应用程序类加载器' : '自定义类加载器' }}
                </VChip>
              </span>
            </template>

            <template #item.classType="{ item }">
              <span class="font-weight-medium">
                {{ getClassType(item.classType) }}
              </span>
            </template>

            <template #item.isFallback="{ item }">
              <span class="font-weight-medium">{{ getIsFallback(item.isFallback) }}</span>
            </template>

            <template #item.version="{ item }">
              <span class="font-weight-medium">{{ item.version }}</span>
            </template>

            <!-- Actions -->
            <template #item.actions="{ item }">
              <IconBtn @click="deleteOper(item)">
                <VIcon icon="tabler-trash" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  删除
                </VTooltip>
              </IconBtn>

              <IconBtn @click="updateOper(item)">
                <VIcon icon="tabler-edit" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  编辑
                </VTooltip>
              </IconBtn>

              <IconBtn @click="execCmp(item)">
                <VIcon icon="tabler-player-play-filled" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  调试
                </VTooltip>
              </IconBtn>
            </template>

            <!-- pagination -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0">
                  共<span style="color: #7367f0;">&nbsp;{{ totalRows }}&nbsp;</span>条记录
                </p>
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalRows / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalRows / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
          <!-- SECTION -->
        </VCard>

        <!-- 👉 类 -->
        
        <ClaEdit
          v-if="addVisible"
          :key="'cmp-edit-'+editKey"
          v-model:isDrawerOpen="addVisible"
          :oper-type="operType"
          :curr-row="currRow"
          :curr-option="option"
          @add-data="addData"
          @update-data="updateData"
        /> 
       
        <!-- 删除确认 -->
        <VDialog
          v-model="deleteVisible"
          width="400"
        >
          <DialogCloseBtn @click="deleteVisible = !deleteVisible" />
          <VCard title="提示">
            <VCardText> 是否删除动态类[{{ deleteName }}]？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="deleteVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="deleteAgreeOper">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>

        <VDialog
          v-model="execVisible"
          scrollable
          width="80%"
          class="ivy-sql-build-dialog"
        >
          <DialogCloseBtn @click="execVisible = !execVisible" />
        
          <VCard>
            <VCardItem class="pb-5">
              <VCardTitle>调试</VCardTitle>
            </VCardItem>
            <VDivider />
            <VCardText>
              <ClaExec :curr-row="currRow" />
            </VCardText>
          </VCard>
        </VDialog>
      </vcol>
    </vrow>
  </section>
</template>



<style lang="scss">
.text-capitalize {
  text-transform: capitalize;
}

.user-list-name:not(:hover) {
  color: rgba(var(--v-theme-on-background), var(--v-medium-emphasis-opacity));
}
</style>
